<?php
/**
 * 收藏表
 */

namespace app\api\model;


use app\common\model\Model;

class Collection extends  Model
{

    const TABLE_NAME = 'collection';
    const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_1;

    protected $name = self::TABLE_NAME;

    public static function addCollection($user_id,$goods_id)
    {
        return self::commonQuery(self::TABLE_NAME)
              ->insert([
                  'user_id'=>$user_id,
                  'goods_id'=>$goods_id,
                  'add_time'=>time()
              ],false,true);
    }
    public static function deleteCollection($collect_id,$user_id)
    {
        $where =['collection_id'=>$collect_id];
        $info = self::commonQuery(self::TABLE_NAME)
              ->where($where)
            ->find();
        if(empty($info) || $info['user_id']!=$user_id)
        {
            return false;
        }
        return self::commonQuery(self::TABLE_NAME)->where($where)->delete();
             
    }
    public static function deleteCollectionByGoodsId($user_id,$goods_id)
    {
        return self::commonQuery(self::TABLE_NAME)
            ->where([
                'user_id'=>$user_id,
                'goods_id'=>$goods_id,
            ])->delete();
    }
    public static function isUserCollection($user_id,$goods_id)
    {
        $info= self::commonQuery(self::TABLE_NAME)
            ->where([
                'user_id'=>$user_id,
                'goods_id'=>$goods_id,
            ])->find();
        return !empty($info);
    }
    public static function getList($user_id,$page=1,$limit=self::LIMIT)
    {
        return self::commonQuery(self::TABLE_NAME)
            ->where(['user_id'=>$user_id])
            ->page($page,$limit)
            ->order('add_time desc')
            ->select();
    }
    public static function handleList($list,$user_id)
    {
        $res = [];
        if(empty($list))
        {
            return $res;
        }
        foreach ($list as $key=>$val)
        {
            $res[$key]=Goods::handleGoodsInfo(
                 Goods::getGoodsInfo($val['goods_id'], self::CACHE_EXPIRE_LEVEL_4)
                ,$user_id);
            $res[$key]['collection_id']=$val['collection_id'];
        }

        return $res;
    }
}